#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
表结构显示组件模块
显示数据库中的表结构
"""

import logging
from typing import Dict, List, Any

from PySide6.QtCore import Qt, QSize, Signal, Slot
from PySide6.QtWidgets import (QWidget, QTreeWidget, QTreeWidgetItem, 
                              QVBoxLayout, QMenu, QPushButton,
                              QLabel, QHBoxLayout, QToolButton, QMessageBox)
from PySide6.QtGui import QIcon, QFont, QAction

from core.db_engine import get_db_engine
from core.i18n import tr


# 初始化日志记录器
logger = logging.getLogger("table_schema")


class TableSchemaWidget(QWidget):
    """表结构显示组件类"""
    
    # 信号定义
    table_selected = Signal(str)  # 选中的表名
    column_selected = Signal(str, str)  # 表名, 列名
    generate_query = Signal(str)  # 生成的查询语句
    table_dropped = Signal(str, bool, str)  # 表名, 成功标志, 消息
    
    def __init__(self, parent=None):
        """初始化表结构显示组件
        
        Args:
            parent: 父窗口
        """
        super().__init__(parent)
        self.db_engine = get_db_engine()
        self._init_ui()
        
    def _init_ui(self):
        """初始化UI"""
        # 主布局
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 标题栏
        title_layout = QHBoxLayout()
        # title_label = QLabel("表结构")
        # title_label.setStyleSheet("font-weight: bold;")
        
        # 刷新按钮
        refresh_button = QToolButton()
        refresh_button.setText(tr("table_schema_refresh", "刷新"))
        refresh_button.setToolTip(tr("table_schema_refresh_tooltip", "刷新表结构"))
        refresh_button.clicked.connect(self.refresh)
        
        # title_layout.addWidget(title_label)
        title_layout.addStretch()
        title_layout.addWidget(refresh_button)
        
        layout.addLayout(title_layout)
        
        # 树形控件
        self.tree = QTreeWidget()
        self.tree.setHeaderLabels([tr("table_schema_header_name", "名称"), tr("table_schema_header_type", "类型")])
        self.tree.setColumnCount(2)
        self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tree.customContextMenuRequested.connect(self._show_context_menu)
        self.tree.itemDoubleClicked.connect(self._handle_item_double_clicked)
        
        # 设置树形控件样式
        # self.tree.setStyleSheet("""
        #     QTreeWidget {
        #         border: 1px solid #ccc;
        #         background-color: #f8f8f8;
        #     }
        #     QTreeWidget::item {
        #         padding: 4px;
        #     }
        #     QTreeWidget::item:selected {
        #         background-color: #0078d7;
        #         color: white;
        #     }
        # """)
        
        layout.addWidget(self.tree)
        
        # 加载表结构
        self.refresh()
        
    def refresh(self):
        """刷新表结构"""
        try:
            self.tree.clear()
            
            # 获取表列表
            tables = self.db_engine.get_loaded_tables()
            
            for table_info in tables:
                table_name = table_info["table_name"]
                
                # 创建表项
                table_item = QTreeWidgetItem(self.tree)
                table_item.setText(0, table_name)
                table_item.setText(1, tr("table_schema_rows_count", "{0} 行").format(table_info.get('row_count', 0)))
                table_item.setData(0, Qt.UserRole, {"type": "table", "name": table_name})
                
                # 设置表项图标和字体
                table_font = QFont()
                table_font.setBold(True)
                table_item.setFont(0, table_font)
                
                # 获取并添加列
                columns = self.db_engine.get_table_schema(table_name)
                for column in columns:
                    column_item = QTreeWidgetItem(table_item)
                    column_item.setText(0, column["name"])
                    column_item.setText(1, column["type"])
                    column_item.setData(0, Qt.UserRole, {
                        "type": "column", 
                        "name": column["name"],
                        "table": table_name
                    })
            
            # 展开第一个表
            if self.tree.topLevelItemCount() > 0:
                self.tree.expandItem(self.tree.topLevelItem(0))
                
            logger.info(tr("table_schema_loaded", "已加载 {0} 个表的结构").format(len(tables)))
            
        except Exception as e:
            logger.error(f"{tr('table_schema_load_failed', '加载表结构失败')}: {str(e)}")
    
    def _show_context_menu(self, position):
        """显示上下文菜单
        
        Args:
            position: 鼠标位置
        """
        item = self.tree.itemAt(position)
        if not item:
            return
            
        data = item.data(0, Qt.UserRole)
        if not data:
            return
            
        menu = QMenu(self)
        
        if data["type"] == "table":
            table_name = data["name"]
            
            # 表操作菜单
            select_all_action = QAction(f'SELECT * FROM "{table_name}"', self)
            select_all_action.triggered.connect(
                lambda: self.generate_query.emit(f'SELECT * FROM "{table_name}";')
            )
            
            count_action = QAction(f'SELECT COUNT(*) FROM "{table_name}"', self)
            count_action.triggered.connect(
                lambda: self.generate_query.emit(f'SELECT COUNT(*) FROM "{table_name}";')
            )
            
            describe_action = QAction(tr("action_view_table_structure", "查看表结构"), self)
            describe_action.triggered.connect(
                lambda: self.generate_query.emit(f'PRAGMA table_info(\'"{table_name}"\');')
            )
            
            # 添加删除表选项
            menu.addAction(select_all_action)
            menu.addAction(count_action)
            menu.addAction(describe_action)
            
            # 添加分隔线
            menu.addSeparator()
            
            # 添加删除表操作
            drop_table_action = QAction(tr("action_drop_table", "删除表"), self)
            drop_table_action.triggered.connect(lambda: self._drop_table(table_name))
            menu.addAction(drop_table_action)
            
        elif data["type"] == "column":
            column_name = data["name"]
            table_name = data["table"]
            
            # 列操作菜单
            select_column_action = QAction(f'SELECT "{column_name}"', self)
            select_column_action.triggered.connect(
                lambda: self.generate_query.emit(
                    f'SELECT "{column_name}" FROM "{table_name}";')
            )
            
            distinct_action = QAction(f'SELECT DISTINCT "{column_name}"', self)
            distinct_action.triggered.connect(
                lambda: self.generate_query.emit(
                    f'SELECT DISTINCT "{column_name}" FROM "{table_name}";')
                )
            
            count_distinct_action = QAction(f'SELECT COUNT(DISTINCT "{column_name}")', self)
            count_distinct_action.triggered.connect(
                lambda: self.generate_query.emit(
                    f'SELECT COUNT(DISTINCT "{column_name}") FROM "{table_name}";')
                )
            
            null_check_action = QAction(tr("action_check_null", "检查NULL值"), self)
            null_check_action.triggered.connect(
                lambda: self.generate_query.emit(
                    f'SELECT COUNT(*) FROM "{table_name}" WHERE "{column_name}" IS NULL;')
                )
            
            menu.addAction(select_column_action)
            menu.addAction(distinct_action)
            menu.addAction(count_distinct_action)
            menu.addAction(null_check_action)
        
        if not menu.isEmpty():
            menu.exec_(self.tree.viewport().mapToGlobal(position))
    
    def _handle_item_double_clicked(self, item, column):
        """处理项目双击事件
        
        Args:
            item: 点击的项目
            column: 点击的列
        """
        data = item.data(0, Qt.UserRole)
        if not data:
            return
            
        if data["type"] == "table":
            self.table_selected.emit(data["name"])
        elif data["type"] == "column":
            self.column_selected.emit(data["table"], data["name"])
    
    def get_tables(self) -> List[str]:
        """获取所有表名
        
        Returns:
            表名列表
        """
        tables = []
        for i in range(self.tree.topLevelItemCount()):
            item = self.tree.topLevelItem(i)
            data = item.data(0, Qt.UserRole)
            if data and data["type"] == "table":
                tables.append(data["name"])
        return tables
    
    def get_columns(self, table_name: str) -> List[str]:
        """获取表的所有列名
        
        Args:
            table_name: 表名
            
        Returns:
            列名列表
        """
        columns = []
        
        # 查找表项
        for i in range(self.tree.topLevelItemCount()):
            item = self.tree.topLevelItem(i)
            data = item.data(0, Qt.UserRole)
            
            if data and data["type"] == "table" and data["name"] == table_name:
                # 获取所有子项（列）
                for j in range(item.childCount()):
                    child = item.child(j)
                    child_data = child.data(0, Qt.UserRole)
                    
                    if child_data and child_data["type"] == "column":
                        columns.append(child_data["name"])
                        
                break
                
        return columns
    
    def _drop_table(self, table_name: str) -> None:
        """删除表
        
        Args:
            table_name: 表名
        """
        # 显示确认对话框
        reply = QMessageBox.question(
            self,
            tr("confirm_drop_table", "确认删除表"),
            tr("confirm_drop_table_message", "确定要删除表 '{0}' 吗？\n此操作不可撤销，所有数据将丢失。").format(table_name),
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No  # 默认按钮为"否"
        )
        
        if reply == QMessageBox.Yes:
            try:
                # 调用数据库引擎删除表
                success, message = self.db_engine.drop_table(table_name)
                
                # 发出表被删除的信号
                self.table_dropped.emit(table_name, success, message)
                
                # 如果成功，刷新表结构视图
                if success:
                    self.refresh()
                    QMessageBox.information(self, tr("drop_table_success", "表 '{0}' 删除成功").format(table_name), message)
                else:
                    QMessageBox.warning(self, tr("drop_table_failed", "删除表失败"), message)
                    
            except Exception as e:
                error_msg = f"{tr('drop_table_failed', '删除表失败')}: {str(e)}"
                logger.error(error_msg)
                QMessageBox.critical(self, tr("drop_table_failed", "删除表失败"), error_msg)
